package com.zlict.admin.service.impl;

import java.util.List;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.zlict.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.zlict.admin.mapper.RdVoucherMapper;
import com.zlict.admin.domain.RdVoucher;
import com.zlict.admin.domain.RdMaterials;
import com.zlict.admin.service.IRdVoucherService;
import com.zlict.admin.service.IRdMaterialsService;

/**
 * 物料领用-单据Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-06-18
 */
@Service
public class RdVoucherServiceImpl implements IRdVoucherService 
{
    @Autowired
    private RdVoucherMapper rdVoucherMapper;
    
    @Autowired
    private IRdMaterialsService rdMaterialsService;

    /**
     * 查询物料领用-单据
     * 
     * @param id 物料领用-单据主键
     * @return 物料领用-单据
     */
    @Override
    public RdVoucher selectRdVoucherById(Long id)
    {
        RdVoucher rdVoucher = rdVoucherMapper.selectRdVoucherById(id);
        if (rdVoucher != null && rdVoucher.getReceiptNumber() != null) {
            // 查询关联的材料列表
            List<RdMaterials> materials = rdMaterialsService.selectRdMaterialsByReceiptNumber(rdVoucher.getReceiptNumber());
            rdVoucher.setMaterials(materials);
        }
        return rdVoucher;
    }

    /**
     * 查询物料领用-单据列表
     * 
     * @param rdVoucher 物料领用-单据
     * @return 物料领用-单据
     */
    @Override
    public List<RdVoucher> selectRdVoucherList(RdVoucher rdVoucher)
    {
        List<RdVoucher> list = rdVoucherMapper.selectRdVoucherList(rdVoucher);
        System.out.println("123");
        // 为每个单据查询关联的材料列表
        for (RdVoucher voucher : list) {
            if (voucher.getReceiptNumber() != null) {
                List<RdMaterials> materials = rdMaterialsService.selectRdMaterialsByReceiptNumber(voucher.getReceiptNumber());
                voucher.setMaterials(materials);
            }
        }
        return list;
    }

    /**
     * 新增物料领用-单据（包含材料）
     * 
     * @param rdVoucher 物料领用-单据
     * @return 结果
     */
    @Override
    @Transactional
    public int insertRdVoucher(RdVoucher rdVoucher)
    {
        // 自动生成单据号
        if (rdVoucher.getReceiptNumber() == null || rdVoucher.getReceiptNumber().trim().isEmpty()) {
            rdVoucher.setReceiptNumber(generateReceiptNumber());
        }
        
        rdVoucher.setCreateTime(DateUtils.getNowDate());
        int result = rdVoucherMapper.insertRdVoucher(rdVoucher);
        
        // 插入关联的材料
        if (result > 0 && rdVoucher.getMaterials() != null && !rdVoucher.getMaterials().isEmpty()) {
            for (RdMaterials material : rdVoucher.getMaterials()) {
                material.setReceiptNumber(rdVoucher.getReceiptNumber());
                rdMaterialsService.insertRdMaterials(material);
            }
        }
        
        return result;
    }

    /**
     * 修改物料领用-单据（包含材料）
     * 
     * @param rdVoucher 物料领用-单据
     * @return 结果
     */
    @Override
    @Transactional
    public int updateRdVoucher(RdVoucher rdVoucher)
    {
        rdVoucher.setUpdateTime(DateUtils.getNowDate());
        int result = rdVoucherMapper.updateRdVoucher(rdVoucher);
        
        // 更新关联的材料：先删除旧的，再插入新的
        if (result > 0 && rdVoucher.getReceiptNumber() != null) {
            // 删除原有的材料
            rdMaterialsService.deleteRdMaterialsByReceiptNumber(rdVoucher.getReceiptNumber());
            
            // 插入新的材料
            if (rdVoucher.getMaterials() != null && !rdVoucher.getMaterials().isEmpty()) {
                for (RdMaterials material : rdVoucher.getMaterials()) {
                    material.setReceiptNumber(rdVoucher.getReceiptNumber());
                    rdMaterialsService.insertRdMaterials(material);
                }
            }
        }
        
        return result;
    }

    /**
     * 批量删除物料领用-单据（包含材料）
     * 
     * @param ids 需要删除的物料领用-单据主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteRdVoucherByIds(Long[] ids)
    {
        // 先删除关联的材料
        for (Long id : ids) {
            RdVoucher rdVoucher = rdVoucherMapper.selectRdVoucherById(id);
            if (rdVoucher != null && rdVoucher.getReceiptNumber() != null) {
                rdMaterialsService.deleteRdMaterialsByReceiptNumber(rdVoucher.getReceiptNumber());
            }
        }
        
        // 再删除单据
        return rdVoucherMapper.deleteRdVoucherByIds(ids);
    }

    /**
     * 删除物料领用-单据信息（包含材料）
     * 
     * @param id 物料领用-单据主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteRdVoucherById(Long id)
    {
        // 先查询单据信息
        RdVoucher rdVoucher = rdVoucherMapper.selectRdVoucherById(id);
        if (rdVoucher != null && rdVoucher.getReceiptNumber() != null) {
            // 删除关联的材料
            rdMaterialsService.deleteRdMaterialsByReceiptNumber(rdVoucher.getReceiptNumber());
        }
        
        // 再删除单据
        return rdVoucherMapper.deleteRdVoucherById(id);
    }

    /**
     * 生成单据号
     * 格式：zlxt+年月日+顺序号（从001开始）
     * 
     * @return 生成的单据号
     */
    @Override
    public String generateReceiptNumber()
    {
        // 获取当前日期
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        String currentDate = dateFormat.format(new Date());
        
        // 构建日期前缀
        String datePrefix = "zlxt" + currentDate;
        
        // 查询当前日期下的最大单据号
        String maxReceiptNumber = rdVoucherMapper.selectMaxReceiptNumberByDate(datePrefix);
        
        int sequenceNumber = 1;
        if (maxReceiptNumber != null && maxReceiptNumber.length() >= 15) {
            // 提取顺序号部分（最后3位）
            String sequenceStr = maxReceiptNumber.substring(maxReceiptNumber.length() - 3);
            try {
                sequenceNumber = Integer.parseInt(sequenceStr) + 1;
            } catch (NumberFormatException e) {
                // 如果解析失败，使用默认值1
                sequenceNumber = 1;
            }
        }
        
        // 格式化顺序号为3位数字，不足补0
        String formattedSequence = String.format("%03d", sequenceNumber);
        
        // 生成完整的单据号
        return datePrefix + formattedSequence;
    }
}
